"""
医生管理 API
严格按照原 Flask 项目的接口实现，保持 100% 兼容性
"""
from fastapi import APIRouter, Depends
# pyright: reportMissingImports=false
from sqlalchemy.ext.asyncio import AsyncSession

from  core.database import get_db
from  api.deps import get_current_active_doctor
from  models.doctor import Doctor
from  schemas.doctor import DoctorCreate, DoctorResponse, DoctorUpdate, DoctorForgotPassword
from  crud import doctor as crud_doctor
from  core.security import verify_password

router = APIRouter()


@router.post("")
async def create_doctor(
    doctor_in: DoctorCreate,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    创建医生
    原接口: POST /api/doctors
    需要JWT认证
    """
    try:
        # 检查手机号是否已存在
        existing_doctor = await crud_doctor.get_by_phone(db, phone=doctor_in.phone)
        if existing_doctor and existing_doctor.status == 1:
            return {
                "message": "该手机号已存在",
                "code": 1
            }
        
        # 创建医生
        doctor = await crud_doctor.create(db, obj_in=doctor_in)
        await db.commit()
        
        return {
            "message": "医生创建成功",
            "id": str(doctor.id),
            "code": 0
        }
        
    except Exception as e:
        await db.rollback()
        return {
            "message": f"创建失败: {str(e)}",
            "code": 1
        }


@router.get("")
async def get_doctors(
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    获取所有医生列表
    原接口: GET /api/doctors
    需要JWT认证
    """
    try:
        # 获取所有活跃医生
        doctors = await crud_doctor.get_all_active(db)
        
        # 使用 Schema 转换为 Flask 格式（不返回密码）
        doctors_data = [
            DoctorResponse.model_validate(d).to_flask_format()
            for d in doctors
        ]
        
        return {
            "message": "获取医生列表成功",
            "data": doctors_data,
            "total": len(doctors_data),
            "code": 0
        }
        
    except Exception as e:
        return {
            "message": f"服务器错误: {str(e)}",
            "code": 1
        }


@router.get("/getOneDoctor")
async def get_one_doctor(
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    获取当前登录医生信息
    原接口: GET /api/doctors/getOneDoctor
    需要JWT认证
    """
    try:
        # 使用 Schema 转换为 Flask 格式
        doctor_data = DoctorResponse.model_validate(current_doctor).to_flask_format()
        
        return {
            "message": "获取医生信息成功",
            "data": doctor_data,
            "code": 0
        }
        
    except Exception as e:
        return {
            "message": f"服务器错误: {str(e)}",
            "code": 1
        }


@router.put("/{doctor_id}")
async def update_doctor(
    doctor_id: str,
    doctor_update: DoctorUpdate,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    更新医生信息
    原接口: PUT /api/doctors/<doctor_id>
    需要JWT认证，只能更新自己的信息
    """
    try:
        # 权限检查：只能更新自己的信息
        if str(current_doctor.id) != doctor_id:
            return {
                "message": "无权更新其他医生的信息",
                "code": 1
            }
        
        # 获取要更新的医生
        try:
            doctor_id_int = int(doctor_id)
        except:
            return {
                "message": "无效的医生ID",
                "code": 1
            }
        
        doctor = await crud_doctor.get(db, id=doctor_id_int)
        if not doctor or doctor.status != 1:
            return {
                "message": "医生不存在",
                "code": 1
            }
        
        # 处理密码更新
        if doctor_update.old_password:
            # 验证旧密码
            if not verify_password(doctor_update.old_password, doctor.password_hash):
                return {
                    "message": "旧密码错误",
                    "code": 1
                }
            
            # 更新为新密码
            if doctor_update.new_password:
                await crud_doctor.update_password(
                    db,
                    doctor=doctor,
                    new_password=doctor_update.new_password
                )
        
        # 验证其他字段
        if doctor_update.phone is not None and not doctor_update.phone:
            return {
                "message": "手机号不能为空",
                "code": 1
            }
        if doctor_update.name is not None and not doctor_update.name:
            return {
                "message": "姓名不能为空",
                "code": 1
            }
        if doctor_update.title is not None and not doctor_update.title:
            return {
                "message": "职称不能为空",
                "code": 1
            }
        
        # 更新其他字段
        update_data = doctor_update.model_dump(
            exclude_unset=True,
            exclude={"password", "old_password", "new_password"}
        )
        
        if update_data:
            # 使用 CRUD 层更新医生信息
            doctor = await crud_doctor.update_doctor_info(
                db,
                doctor=doctor,
                update_data=update_data
            )
            await db.commit()
            await db.refresh(doctor)
        
        return {
            "message": "医生信息更新成功",
            "code": 0,
            "data": {
                "_id": str(doctor.id),
                "updated_at": doctor.updated_at.isoformat() if doctor.updated_at else None
            }
        }
        
    except Exception as e:
        await db.rollback()
        return {
            "message": f"更新失败: {str(e)}",
            "code": 1
        }


@router.delete("/{doctor_id}")
async def delete_doctor(
    doctor_id: str,
    db: AsyncSession = Depends(get_db),
    current_doctor: Doctor = Depends(get_current_active_doctor)
):
    """
    删除医生（软删除）
    原接口: DELETE /api/doctors/<doctor_id>
    需要JWT认证，不能删除自己
    """
    try:
        # 不允许删除自己
        if str(current_doctor.id) == doctor_id:
            return {
                "message": "不能删除当前登录的账号",
                "code": 1
            }
        
        # 获取要删除的医生
        try:
            doctor_id_int = int(doctor_id)
        except:
            return {
                "message": "无效的医生ID",
                "code": 1
            }
        
        doctor = await crud_doctor.get(db, id=doctor_id_int)
        if not doctor or doctor.status != 1:
            return {
                "message": "医生不存在",
                "code": 1
            }
        
        # 使用 CRUD 层软删除
        await crud_doctor.soft_delete(db, doctor=doctor)
        await db.commit()
        
        return {
            "message": "医生删除成功",
            "code": 0
        }
        
    except Exception as e:
        await db.rollback()
        return {
            "message": f"删除失败: {str(e)}",
            "code": 1
        }


@router.post("/forgot-password")
async def forgot_password(
    forgot_data: DoctorForgotPassword,
    db: AsyncSession = Depends(get_db)
):
    """
    忘记密码（重置为默认密码123456）
    原接口: POST /api/doctors/forgot-password
    不需要JWT认证
    """
    try:
        # 查找医生
        doctor = await crud_doctor.get_by_phone_and_name(
            db,
            phone=forgot_data.phone,
            name=forgot_data.name
        )
        
        if not doctor:
            return {
                "message": "未找到匹配的医生信息",
                "code": 1
            }
        
        # 重置密码为默认密码123456
        await crud_doctor.reset_password(db, doctor=doctor, default_password="123456")
        await db.commit()
        
        return {
            "message": "密码已重置为默认密码123456",
            "code": 0
        }
        
    except Exception as e:
        await db.rollback()
        return {
            "message": f"密码重置失败: {str(e)}",
            "code": 1
        }


